package code.web.controller;

import code.dto.ResultDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@Controller
@RequestMapping("/redis")
@Api(value = "Redis", tags = {"Redis相关接口"})
public class RedisController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PostMapping("set")
    @ApiOperation("写入")
    public ResultDto<?> set(String key, String value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return ResultDto.success();
        } catch (Exception e) {
            throw new RuntimeException("写入失败: " + e.getMessage(), e);
        }
    }

    @GetMapping("get")
    @ApiOperation("读取")
    public ResultDto<String> get(String key) {
        String get = redisTemplate.opsForValue().get(key);
        return ResultDto.ok(get);
    }

    @GetMapping("timeout")
    @ApiOperation("设置key过期")
    public ResultDto<Boolean> expire(String key, Integer timeout) {
        Boolean expire = redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
        if (Boolean.TRUE.equals(expire)) {
            return ResultDto.ok(expire);
        }
        return ResultDto.failed();
    }
}
